# -*- coding: utf-8 -*-

from PyQt5.QtCore import QThread
from selenium import webdriver
from time import sleep
from os.path import exists
from os import remove
from pickle import dump, load
import requests


class Cookie(QThread):
    # sig = pyqtSignal(int)

    def __init__(self, parent=None):
        super().__init__(parent)

    def get_cookie(self):
        login_url = "https://passport.damai.cn/login"
        if not exists("cookies.pkl"):
            driver = webdriver.Chrome()
            driver.get(login_url)
            print("###请扫码登录###")
            while driver.title == '大麦登录':  # 等待扫码完成
                sleep(1)
                # TODO: switch to qrcode
                if not exists("qr.png"):
                    # 切换到iframe内容
                    driver.switch_to.frame("alibaba-login-box")
                    # 点击扫码登陆
                    driver.find_element_by_xpath("/html/body/div[1]/div/div[1]/div[3]").click()
                    sleep(1)
                    url = driver.find_element_by_xpath('//*[@id="login"]/div[2]/div/div[2]/div[1]/img').get_attribute(
                        "src")
                    print(url)
                    # TODO: display qr code on ui
                    req = requests.get(url)
                    with open("qr.png", "wb") as f:
                        f.write(req.content)
                    sleep(2)
                else:
                    pass
            dump(driver.get_cookies(), open("cookies.pkl", "wb"))
            driver.quit()
            remove('qr.png')
            print("###Cookie保存成功###")

    def login(self):
        if not exists('cookies.pkl'):  # 如果不存在cookie.pkl,就获取一下
            self.get_cookie()
        print('###打开浏览器，进入大麦网###')
        # 设置不载入图片，提高刷新效率
        options = webdriver.ChromeOptions()
        prefs = {"profile.managed_default_content_settings.images":2} # 禁止加载图片
        options.add_experimental_option("prefs",prefs)
        driver = webdriver.Chrome(options=options)
        driver.get(self.target_url)
        driver.set_cookie()
        driver.refresh()
        driver.quit()
        # TODO:check login success
        # try:
